//动态注册路由组件
//路由文件名不得重复
const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const DIR_NAME = './'


const routes = {}

//排除路由文件夹根文件，并且以下同名的路由文件不会被自动注册，如若必须使用，请手动给routes对象添加该路由组件
const excluding = ['index', 'routes']

const ROUTE_ROOT_PATH = path.resolve(__dirname, DIR_NAME) + '/'


function listDir(dir){
  let fileList = fs.readdirSync(dir,'utf-8');
  for(let i=0; i < fileList.length; i++) {
    let stat = fs.lstatSync(dir + fileList[i]);
    // 是目录，需要继续
    if (stat.isDirectory()) {
      listDir(dir + fileList[i]  + '/');
    } else {
      if (excluding.indexOf(fileList[i].split('.')[0]) === -1) {
        nameArr.push(fileList[i])
        routes[fileList[i].split('.')[0]] = require(dir + fileList[i])
      }
    }
  }
}
const nameArr = []
listDir(ROUTE_ROOT_PATH)

if (nameArr.length > new Set(nameArr).size) {
  console.log(chalk.red('error: 路由组件文件名存在重复，此错误会引起同名路由前者会被后者覆盖'))
}

module.exports = routes